package com.kuangstudy.config.security;

import com.kuangstudy.fiter.JwtAuthenticationTokenFilter;
import com.kuangstudy.handler.MyAccessDeniedHandler;
import com.kuangstudy.handler.MyAuthenticationEntryPointHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Description:
 * Author: ryt
 * Version: 1.0
 * Create Date Time: 2021/12/21 16:26.
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)  // 开启权限的功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private MyAuthenticationEntryPointHandler myAuthenticationEntryPointHandler;

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    // 创建一个 BCryptPasswordEncoder 注入到容器中
    // 密码加密器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // spring容器中暴露AuthenticationManager对象
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 认证相关的配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭csrf防护
                .csrf().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/login/user").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        // 将自定义认证失败处理器 和 自定义授权失败处理器 配置到Security中
        http.exceptionHandling()
                // 认证失败处理器
                .authenticationEntryPoint(myAuthenticationEntryPointHandler)
                // 授权失败处理器
                .accessDeniedHandler(myAccessDeniedHandler);

        // 将自定义的认证过滤器 放入到  UsernamePasswordAuthenticationFilter 过滤器 执行之前 进行执行！
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 允许跨域
        http.cors();
    }
}
